import sqlite3
from config import dbFile
from loguru import logger

def dict_factory(cursor, row):
    d = {}
    for index, col in enumerate(cursor.description):
        d[col[0]] = row[index]
    return d


class Sqlite(object):
    def __init__(self):
        """
        初始化函数，创建数据库连接
        """
        self.conn = sqlite3.connect(dbFile,check_same_thread=False)
        self.conn.row_factory = dict_factory
        self.cursor = self.conn.cursor()

    def commit(self, sql):
        """
        数据库数据查询
        :param sql: 传入的SQL语句
        :return: 返回操作数据库状态
        """
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            logger.error(f"数据库报错:{e}")
            self.conn.rollback()
            raise
            
    def query(self, sql):
        """
        数据库数据查询
        :param sql: 传入的SQL语句
        :return: 返回操作数据库状态
        """
        try:
            self.cursor.execute(sql)
            data = self.cursor.fetchall()
            return data
        except Exception as e:
            logger.error(f"数据库报错:{e}")
            raise


    def close(self):
        """
        关闭数据库相关连接的函数
        :return:
        """
        self.cursor.close()
        self.conn.close()
